/*global self, pi, postMessage */

/**
 * 计算线程：进行渲染计算
 * 消息种类：
 * 1. 计算消息：
 *	{
 *		type: "compute",
 *		id: 代表该请求的唯一数字,
 *		data: {
 *			context: 渲染环境句柄,
 *			handle: 字节缓冲的句柄
 *		}
 *	}
 *	返回:
 *	{
 *		type: "compute",
 *		id: 代表该请求的唯一数字,
 *		data: 成功用于渲染的字节缓冲句柄，失败返回{error: , reason: }
 *	}
 */

pi.mod.define('pi.worker.compute', function (pi) {
	"use strict";
	var module = {};
	module.init = function () {
		var table = {};

		/* 处理计算消息 */
		table.compute = function (data) {
			var h = 0;
			if (pi.lang.isObject(data)) {
				h = pi.render.t3d.calculate(data.context, data.handle);
				if (h === 0) {
					h = {
						error: 4,
						reason: "compute worker, pi.render.t3d.calculate = 0"
					};
				}
			} else {
				h = {
					error: 3,
					reason: "compute worker, data isn't object"
				};
			}
			return h;
		};
		return table;
	};

	module.onmessage = function (e) {
		var fun, res = 0,
			req = e.data;
		if (req === "quit") {
			self.close();
		} else if (pi.lang.isObject(req)) {
			if (module.methodTable === undefined) {
				module.methodTable = module.init();
			}

			if (module.methodTable && req.type) {
				fun = module.methodTable[req.type];
				if (fun !== undefined) {
					res = fun(req.data);
				} else {
					res = {
						error: 2,
						reason: "compute worker, type isn't function name"
					};
				}
			} else {
				res = {
					error: 1,
					reason: "compute worker, slef.methodTable && req.type"
				};
			}

			postMessage({
				type: req.type,
				id: req.id,
				data: res
			});
		}
	};
	return module;
});